<?php

class Smartyclass {

	public $smarty = null;

	function __construct()
	{

		require_once (SMARTY_DIR.'Smarty.class.php');

		$this->smarty = new Smarty();
		$this->smarty->setCompileDir(APPPATH.'/data/templates_c')
			->addPluginsDir(APPPATH.'/plugins')
			->setCacheDir(APPPATH.'/data/cache');

		$this->smarty->default_resource_type = 'mysql';

		$this->CI =& get_instance();
		$this->CI->load->library('Smarty_mysql_resource');

		$this->smarty->registerObject('db', $this->CI->db);

		$this->smarty->registerResource('mysql', $this->CI->smarty_mysql_resource);
		$this->smarty->registerFilter("output", "hrefToRAW");

	}

	public function checkTemplate($source)
	{

		$mesg = '';
		$line = 0;

		//the programm should not compile {main} tag. Replace it.
		$source = preg_replace ("/\{main\}/", "{*main*}", $source);

		$tpl = $this->smarty->createTemplate('string:'.$source);

		$prev_state = error_reporting();
		error_reporting(0);
		try {
			error_reporting(0);
			$tpl->compiler->compileTemplate($tpl);
		} catch (Exception $e) {
			$mesg = $e->getMessage();
			$mesg = preg_replace ('/in template "[^"]+"/', '', $mesg);
			preg_match('/line (\d+) /', $mesg, $a);
			$line = $a[1];
		}

		error_reporting($prev_state);

		return array ($line, $mesg);

	}


}

function insert_header($params)
{
   // эта функция ожидает аргумент $content
   if (empty($params['content'])) {
       return;
   }
   header($params['content']);
   return;
}

function hrefToRAW ($tpl_output, Smarty_Internal_Template $template) {

	if (preg_match ('/^<\?xml /', $tpl_output))
		return $tpl_output;

	$prev_state = error_reporting();
	#error_reporting(0);

	$dom = new DOMDocument();
	$dom->strictErrorChecking = false;
	$dom->preserveWhiteSpace = true;
	$dom->formatOutput = false;
	$dom->recover = false;
	$tpl_output=preg_replace('/^\t+/m', '',$tpl_output);
	$tpl_output=preg_replace('/<head[^>]*>/','<head>
		<meta http-equiv="content-type" content="text/html; charset=utf-8">
		',$tpl_output);
  	$dom->loadHTML('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'.$tpl_output);
	$tpl_output = $dom->saveHTML();

	error_reporting($prev_state);
	$tpl_output=preg_replace('#<meta http-equiv="content-type" content="text/html; charset=utf-8">(\r)?\n#', '', $tpl_output, 1);

	return $tpl_output;

}
